PHP operates MongoDB to realize the function of adding deleting modifying and checking [with php7 operating MongoDB method]

  • 2021-09-24 21:43:41
  • OfStack

In this paper, PHP operates MongoDB to realize the function of adding, deleting, modifying and checking. Share it for your reference, as follows:

The PHP driver of MongoDB provides some core classes to operate MongoDB. Generally speaking, some functions in MongoDB command line can be realized, and the format of parameters is basically similar. The operation of MongoDB before PHP7 is different from that after PHP7. This paper mainly takes the previous version of PHP7 as an example to explain various operations of PHP to MongoDB, and finally briefly explains the operation of MongoDB after PHP7 under 1.

1. Data insertion


//insert()
// Parameter 1 : 1 Arrays or objects 
// Parameter 2 : Extension Options 
// fsync Default to false If it is true Then mongo Data will be forced to be written to the hard disk before confirming that the data insertion is successful 
// j Default to false If it is true Then mongo The data will be forced to be written to the log before the data insertion is confirmed to be successful 
// w Default to 1 The write operation will be confirmed by the (primary) server, if it is 0 Will not be confirmed, set to when using replica sets n Used to ensure that the primary server successfully replicates data modifications to the n Confirm after 10 nodes 
// wtimeout Default to 10000 (milliseconds), which specifies how long the server waits to receive acknowledgements 
// timeout Specifies the timeout (in milliseconds) that the client needs to wait for the server to respond 
$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;// Select a database 
$collection = $db->friend;// Select a document collection 
$doc = [// Definition 1 Documents, namely 1 Array of numbers 
  'First Name' => 'Jet',
  'Last Name' => 'Wu',
  'Age' => 26,
  'Phone' => '110',
  'Address' => [
    'Country' => 'China',
    'City' => 'Shen Zhen'
  ],
  'E-Mail' => [
    '123456@qq.com',
    '666666@sina.com',
    '8888888@qq.com',
    '77887788@qq.com'
  ]
];
$res = $collection->insert($doc);// Insert into the collection 1 Documents 
echo '<pre>';
print_r($res);//$res['ok']=1 Indicates successful insertion 

2. Data query

1. Query a single document:


//findOne()
// Parameter 1 : Search criteria 
// Parameter 2 Specifies the return field, array('fieldname' => true, 'fieldname2' => true) . _id Field will always return unless in the 2 Parameters are explicitly added '_id'=>false . Return all fields if not set 
$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;
$collection = $db->friend;
$one = $collection->findOne(['First Name' => 'Jet']);
echo '<pre>';
print_r($one);// Return 1 Array, and return if no data is found NULL

2. Query multiple documents:


//find()
// Parameter 1 : Search criteria 
// Parameter 2 Specifies the return field, array('fieldname' => true, 'fieldname2' => true) . _id Field is always returned unless explicitly set to false Do not return. Return all fields if not set 
$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;
$collection = $db->friend;
$cursor = $collection->find(['Address.Country' => 'China']);// Finding Array Elements Using the Dot Operator 
echo '<pre>';
while($doc = $cursor->getNext()) {// Loop to read each matching document 
  print_r($doc);
}

Define queries using various conditional operators:


//mongodb Use separately $lt , $lte , $eq , $gte , $gt , $ne Denote < , <= , = , >= , > , <> For integer field queries 
$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;
$collection = $db->friend;
$cursor = $collection->find(['Age' => ['$gt' => 30]]);
echo '<pre>';
while($doc = $cursor->getNext()) {
  print_r($doc);
}
// Query all non-duplicate values of a field 
$res = $collection->distinct('Age');
//$in Matches any of multiple values 1 A 
$cursor = $collection->find(['Address.Country' => ['$in' => ['China', 'USA']]]);
//$all Matches all of multiple values (for array field queries) 
$cursor = $collection->find(['E-Mail' => ['$all' => ['123456@qq.com', '77887788@qq.com']]]);
//$or : Or query 
$cursor = $collection->find(['$or' => [['First Name' => 'Jet'], ['Address.Country' => 'USA']]]);
//$slice Gets the specified number of elements in an array field located in the find() Function number 2 Of the parameters 
$cursor = $collection->find(['First Name' => 'Jet'], ['E-Mail' => ['$slice' => 2]]);// Returns only the first two email
$cursor = $collection->find(['First Name' => 'Jet'], ['E-Mail' => ['$slice' => -2]]);// Returns only the last two email
$cursor = $collection->find(['First Name' => 'Jet'], ['E-Mail' => ['$slice' => [1, 2]]]);// Ignore the 1 Returns the next two 
//$exists Query based on whether a field has a set value 
$cursor = $collection->find(['Hobby' => ['$exists' => false]]);// Find Hobby Documents with no value set for the field 
// Regular expression query 
$cursor = $collection->find(['First Name' => new MongoRegex('/^Je/i')]);// Find First Name Field with Je The document at the beginning, ignoring case differences 

Use other functions provided by the MongoCursor class:


// Sort: 1 Ascending order, -1 Descending order 
$cursor->sort(['Age' => 1]);
// Before ignoring n Matching documents 
$cursor->skip(1);
// Before returning only n Matching documents ( limit() And skip() Use in combination to realize data paging function) 
$cursor->limit(1);
// Total number of matching documents 
$cursor->count();
// Specify the query index 
$cursor->hint(['Last Name' => -1]);// If the index does not exist, an error will be reported 

Aggregate query: group statistics of data


// Aggregation query: group statistics of data 
$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;
$collection = $db->friend;
$res = $collection->aggregate([
  '$group' => [
    '_id' => '$Address.Country',// Grouping field, be careful to add " $ ", which is grouped according to the value of an element in an array field 
    'total' => ['$sum' => 1],// Summation, indicating that every match 1 The sum of documents is added 1
    'maxAge' => ['$max' => '$Age'],// In grouping Age Maximum value of field 
    'minAge' => ['$min' => '$Age']// In grouping Age Minimum value of field 
  ]
]);
echo '<pre>';
print_r($res);// Return 1 An array of, $ret['result'] Is an array for storing statistical results 
// Aggregate query with other operations: The order of execution among multiple operations depends on the order of their positions 
// Aggregate all operations in the query, including '$group' Inside, they are all optional. 
$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;
$collection = $db->friend;
$res = $collection->aggregate([
  [// Filter criteria: Only the original documents that meet the criteria are aggregated. If they are placed in the '$group' After that, only qualified result documents are returned 
    '$match' => ['Age' => ['$gt' => 30]]
  ],
  [// Specify grouping fields, statistics fields 
    '$group' => [
      '_id' => '$Address.Country',
      'totalAge' => ['$sum' => '$Age']// Calculate individual groupings Age Sum of fields 
    ]
  ],
  // If the following operations are placed '$group' Before, it acts on the original document before aggregation. If you put it in the '$group' It then acts on the result document after aggregation 
  ['$unwind' => '$E-Mail'],// Split a document containing an array type field into multiple documents, and the value of the same name field in each document is in the array 1 A value. 
  ['$project' => ['myAge' => '$Age', 'First Name' => '$First Name']],// Specify the return field, which can be renamed. Format: Return field name  => $ Original field name 
  ['$skip' => 2],// Skip a specified number of documents 
  ['$limit' => 2],// Returns only a specified number of documents 
  ['$sort' => ['totalAge' => 1]]// Sort 
]);
echo '<pre>';
print_r($res);

3. Data modification


//update()
//参数1:更新条件,指定更新的目标对象。
//参数2:指定用于更新匹配记录的对象。
//参数3:扩展选项组。
// upsert:若设置为true,当没有匹配文档的时候会创建1个新的文档。
// multiple:默认为false,若设置为true,匹配文档将全部被更新。
// fsync:若设置为true,w参数将被覆盖为0,数据将在更新结果返回前同步到磁盘。
// w:默认为1;若设置为0,更新操作将不会得到确认;使用复制集时可设置为n,确保主服务器在将修改复制到n个节点后才确认该更新操作
// j:默认为false,若设置为true,数据将在更新结果返回之前写入到日志中。
// wtimeout:默认为10000(毫秒),用于指定服务器等待接收确认的时间
// timeout:指定客户端需要等待服务器响应的超时时间(毫秒)
//注意:若不使用任何修改操作符,则匹配文档将直接被整个替换为参数2指定的对象。
//$inc:增加特定键的值,若字段不存在则新建字段并赋值
$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;
$collection = $db->friend;
$res = $collection->update(['First Name' => 'Jet'], ['$inc' => ['Age' => 2]]);
echo '<pre>';
print_r($res);//$res['ok']=1表示修改成功,$res['nModified']表示修改的文档数量
//$set:重置特定键的值,若字段不存在则新建字段并赋值
$res = $collection->update(['First Name' => 'Jet'], ['$set' => ['Hobby' => 'pingpong']]);
//$unset:删除字段
$res = $collection->update(['First Name' => 'Jet'], ['$unset' => ['Hobby' => 1]]);
//$rename:重命名字段,若字段不存在则不进行任何操作
$res = $collection->update(['First Name' => 'Jet'], ['$rename' => ['Hobby' => 'hobby', 'Age' => 'age']]);
//注意:如果文档中已经使用了指定名称的字段,则该字段将会被删除,然后再进行重命名操作。
//$setOnInsert:设置了upsert为true,并且发生了插入操作的时候,将某个字段设置为特定的
$res = $collection->update(['First Name' => 'jet'], ['$setOnInsert' => ['lang' => 'English']], ['upsert' => true]);
//$push:向指定字段添加1个值(作用于数组字段),若字段不存在会先创建字段,若字段值不是数组会报错
$res = $collection->update(['First Name' => 'Jet'], ['$push' => ['E-Mail' => '123123@qq.com']]);
//$push:向指定字段添加多个值(作用于数组字段),若字段不存在会先创建字段,若字段值不是数组会报错
$res = $collection->update(['First Name' => 'Jet'], ['$pushAll' => ['E-Mail' => ['666@qq.com', '8888888@qq.com']]]);
//使用$push和$each向某个字段添加多个值(作用于数组字段),若字段不存在会先创建字段,若字段值不是数组会报错
$res = $collection->update(['First Name' => 'Jet'], ['$push' => ['E-Mail' => ['$each' => ['123123@qq.com', '666@qq.com']]]]);
//$addToSet:将数据添加到数组中(只在目标数组没有该数据的时候才将数据添加到数组中)
$res = $collection->update(['First Name' => 'Jet'], ['$addToSet' => ['E-Mail' => '123123@qq.com']]);
$res = $collection->update(['First Name' => 'Jet'], ['$addToSet' => ['E-Mail' => ['$each' => ['123123@qq.com', '666@qq.com']]]]);
//$pop:从数组中删除1个元素,-1表示删除第1个元素,1表示删除最后1个元素(其实负数都删除第1个元素,0或正数都删除最后1个元素)
$res = $collection->update(['First Name' => 'Jet'], ['$pop' => ['E-Mail' => 1]]);
//$pull:删除数组中所有指定值
$res = $collection->update(['First Name' => 'Jet'], ['$pull' => ['E-Mail' => '123123@qq.com']]);
//$pullAll:删除数组中多个元素的所有值
$res = $collection->update(['First Name' => 'Jet'], ['$pullAll' => ['E-Mail' => ['123123@qq.com', '666@qq.com']]]);
//save()
//参数1:希望保存的信息数组
//参数2:扩展选项
// fsync:若设置为true,w参数将被覆盖为0,数据将在更新结果返回前同步到磁盘。
// w:默认为1;若设置为0,更新操作将不会得到确认;使用复制集时可设置为n,确保主服务器在将修改复制到n个节点后才确认该更新操作
// j:默认为false,若设置为true,数据将在更新结果返回之前写入到日志中。
// wtimeout:默认为10000(毫秒),用于指定服务器等待接收确认的时间
// timeout:指定客户端需要等待服务器响应的超时时间(毫秒)
//注意:若已存在则更新,若不存在则插入;更新时使用参数1指定的信息数组替换整个文档。
//若想更新则应该在参数1中指定_id键的值。
$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;
$collection = $db->friend;
$doc = [//定义1个文档,即1个数组
  'First Name' => 'Jet',
  'Last Name' => 'Wu',
  'Age' => 26,
  'Phone' => '110',
  'Address' => [
    'Country' => 'China',
    'City' => 'Shen Zhen'
  ],
  'E-Mail' => [
    '123456@qq.com',
    '666666@sina.com',
    '8888888@qq.com',
    '77887788@qq.com'
  ]
];
$res = $collection->save($doc);
echo '<pre>';
print_r($res);//$res['ok']=1表示操作成功,$res['updatedExisting']=1表示更新,$res['upserted']=1表示插入
//findAndModify()
//参数1:指定查询条件
//参数2:指定用于更新文档的信息
//参数3:可选,指定希望返回的字段
//参数4:扩展选项
// sort:以特定顺序对匹配文档进行排序
// remove:若设置为true,第1个匹配文档将被删除
// update:若设置为true,将在被选择的文档上执行更新操作
// new:默认为false,若设置为true则返回更新后的文档,否则返回更新前的文档
// upsert:若设置为true,没有找到匹配文档的时候将插入1个新的文档
$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;
$collection = $db->friend;
$res = $collection->findAndModify(['First Name' => 'Jet'], ['$push' => ['E-Mail' => '111@qq.com']]);
echo '<pre>';
print_r($res);

4. Data deletion


//remove()
// Parameter 1 Query Criteria 
// Parameter 2 : Extension Options 
// justOne If set to true , there is only at most 1 Matching documents will be deleted 
// fsync If set to true , w Parameter will be overridden with 0 Data is synchronized to disk before the update results are returned. 
// w Default to 1 ; If set to 0 The update operation will not be confirmed; When using replica sets, you can set to n Ensure that the primary server replicates the changes to the n The update operation is confirmed after 10 nodes 
// j Default to false If set to true Data is written to the log before the update results are returned. 
// wtimeout Default to 10000 (milliseconds), which specifies how long the server waits to receive acknowledgements 
// timeout Specifies the timeout (in milliseconds) that the client needs to wait for the server to respond 
$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;
$collection = $db->friend;
$res = $collection->remove(['First Name' => 'jet']);
echo '<pre>';
print_r($res);//$res['n'] Indicates that several documents have been deleted 

The above is the MongoDB operation before PHP7, and the following is a brief introduction to the operation after PHP7.

PHP7 Operating Methods

Data insertion:


$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['name' => 'JetWu5', 'age' => 26]);
$bulk->insert(['name' => 'JetWu6', 'age' => 26]);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);// Optional, modify confirmation 
$res = $manager->executeBulkWrite('wjt.friend', $bulk, $writeConcern);
echo '<pre>';
print_r($res);

Data query:


$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$query = new MongoDB\Driver\Query(['age' => 24], ['sort' => ['age' => 1]]);
$cursor = $manager->executeQuery('wjt.friend', $query);
$data = [];
foreach($cursor as $doc) {
  $data[] = $doc;
}
echo '<pre>';
print_r($data);

Data modification:


//findOne()
// Parameter 1 : Search criteria 
// Parameter 2 Specifies the return field, array('fieldname' => true, 'fieldname2' => true) . _id Field will always return unless in the 2 Parameters are explicitly added '_id'=>false . Return all fields if not set 
$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;
$collection = $db->friend;
$one = $collection->findOne(['First Name' => 'Jet']);
echo '<pre>';
print_r($one);// Return 1 Array, and return if no data is found NULL

0

Data deletion:


//findOne()
// Parameter 1 : Search criteria 
// Parameter 2 Specifies the return field, array('fieldname' => true, 'fieldname2' => true) . _id Field will always return unless in the 2 Parameters are explicitly added '_id'=>false . Return all fields if not set 
$mongo = new MongoClient('mongodb://localhost:27017');
$db = $mongo->mf;
$collection = $db->friend;
$one = $collection->findOne(['First Name' => 'Jet']);
echo '<pre>';
print_r($one);// Return 1 Array, and return if no data is found NULL

1

For more readers interested in PHP related contents, please check the topics of this site: "PHP+MongoDB database operation skills", "PHP database operation skills summary based on pdo", "php object-oriented programming introduction tutorial", "php string (string) usage summary", "php+mysql database operation introduction tutorial" and "php common database operation skills summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: